/**
 * 
 */
package com.mnjpcorp.shopping.security;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * Secures the database by updating user passwords.
 * 
 * @author nhn
 */
public class DatabasePasswordSecurerBean extends JdbcDaoSupport {
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private SaltSource saltSource;

	@Autowired
	private UserDetailsService userDetailsService;

	public void secureDatabase() {
		getJdbcTemplate().query("select user_id, user_password from tbl_users where user_id='nt10217'", new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				String username = rs.getString(1);
				String password = rs.getString(2);

				UserDetails user = userDetailsService.loadUserByUsername(username);
				String encodedPassword = passwordEncoder.encodePassword(password, saltSource.getSalt(user));
				System.out.println("Original password : " + password);
				System.out.println("Encoded password with salt : " + encodedPassword);
				System.out.println("Encoded Password : " + passwordEncoder.encodePassword(password, null));
				getJdbcTemplate().update("update tbl_users set user_password = ? where user_id = ?", encodedPassword, username);

				logger.debug("Updating password for username: " + username + " to: " + encodedPassword);
			}
		});
	}
}
